package com.example.myapplication

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.ContentObserver
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.telephony.SmsMessage
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS), 2)

    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] == 0) {

            val filter = IntentFilter()//方式1
            filter.addAction("android.provider.Telephony.SMS_RECEIVED")
            val receiver = SmsReceiver()
            registerReceiver(receiver, filter)//注册广播接收器


//            smsObserver = SmsObserver(smsHandler,this); // 方式2
//            contentResolver.registerContentObserver(Uri.parse("content://sms/"), true, smsObserver);

        }

    }


    private lateinit var smsObserver: SmsObserver

    class SmsReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val content = StringBuilder() //用于存储短信内容

            var sender: String? = ""//存储短信发送方手机号

            val bundle = intent!!.extras //通过getExtras()方法获取短信内容

            val format = intent.getStringExtra("format")
            if (bundle != null) {
                val pdus = bundle["pdus"] as Array<*> //根据pdus关键字获取短信字节数组，数组内的每个元素都是一条短信
                var message: SmsMessage

                for (ob in pdus) {
                    if (Build.VERSION.SDK_INT < 23) {
                        message = SmsMessage.createFromPdu(ob as ByteArray?)
                    } else {
                        message = SmsMessage.createFromPdu(ob as ByteArray?, format)
                    }
                    sender = message.originatingAddress //获取短信手机号
                    content.append(message.messageBody) //获取短信内容

                }

                Log.e("111111发送者", "onReceive: $sender")
                Log.e("111111_内容", "onReceive: $content")
            }

        }

    }

    class SmsObserver(private var activity: MainActivity, handler: Handler?) : ContentObserver(handler) {
        override fun onChange(selfChange: Boolean, uri: Uri?) {
            super.onChange(selfChange, uri)

            Log.e("111", "onChange: " + uri.toString())

            val cursor: Cursor? = activity.contentResolver.query(Uri.parse("content://sms/outbox"), null, null, null, "date desc")

            val inCursor: Cursor? = activity.contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, "date desc")

            inCursor?.let {
                while (it.moveToNext()) {
                    val stringBuilder = StringBuffer()
                    stringBuilder.append("address=" + it.getString(it.getColumnIndex("address")))
                    stringBuilder.append(";subject=").append(it.getString(it.getColumnIndex("subject")))
                    //内容
                    stringBuilder.append(";body=").append(it.getString(it.getColumnIndex("body")))
                    //发送时间
                    val dateNumber = it.getString(it.getColumnIndex("date"))
                    //把毫秒值的时间值（1487314423408）转换成（2017-02-17 15:02:22）
                    val time = dateNumber.toLongOrNull()
                    Log.d("GsonUtils", "time=$time")
                    Log.e("收件箱", "stringBuilder=$stringBuilder")
                }
            }

            cursor?.let {
                while (it.moveToNext()) {
                    val stringBuilder = StringBuffer()
                    stringBuilder.append("address=" + it.getString(it.getColumnIndex("address")))
                    stringBuilder.append(";subject=").append(cursor.getString(cursor.getColumnIndex("subject")))
                    //内容
                    stringBuilder.append(";body=").append(cursor.getString(cursor.getColumnIndex("body")))
                    //发送时间
                    val dateNumber = cursor.getString(cursor.getColumnIndex("date"))
                    //把毫秒值的时间值（1487314423408）转换成（2017-02-17 15:02:22）
                    Log.e("发件箱", "stringBuilder=$stringBuilder" + "dateNumber=" + dateNumber)
                }
            }


        }
    }

}

